import Modal from 'antd/lib/modal/Modal';
import { Form, Input, Button, Statistic, message } from 'antd';
import React, { memo, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { changePhoneVisible, changeshowModalActiom, changeRegister, getLoginSucceedInfoAction } from '../../store/actionCreators';
import { RegisterWrapper, QRCode } from './styled';
import { mask } from '@/tools/math';
import { code, verificationCode, IsRegister } from '@/netWork/login';
import Draggable from 'react-draggable';
const Register = memo((props) => {
  // state and props
  const [ bounds, setBounds] = useState({ bounds: { left: 0, top: 0, bottom: 0, right: 0 },})
  //Hooks
  const [isPass, setIsPass] = useState(0)
  const [disabled, setDisabled] = useState(true)
  const [disabled2, setDisabled2] = useState(true)
  const [phone, setPhone] = useState(10086)
  const [password, setPassword] = useState("0.0123demo")
  const [verifyCode, setVerifyCode] = useState(1234)
  const [isCountDown, setCountDown] = useState(true)
  const dispatch = useDispatch()
  const nextRef = useRef()
  const draggleRef = useRef()
  const { isShowRegister } = useSelector((state) => {
    return {
      phoneVisible: state.getIn(["login", "phoneVisible"]),
      liginSucceedInfo: state.getIn(["login", "liginSucceedInfo"]),
      isShowRegister: state.getIn(["login", "isShowRegister"])
    }
  })
  useEffect(() => {
  }, [isShowRegister])
  useEffect(() => {
    if(phone!==10086){
        code(phone).then(res=>{})
    }
    console.log(phone,124);
  }, [phone,verifyCode])
  // function
  const handleCancel = () => {
    dispatch(changePhoneVisible(false))
    dispatch(changeRegister(false))
  }
  //表单function
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  }
  const onFinish = (values) => {
    setPhone(values.username)
    setPassword(values.password)
  };
  const inputChange = (e) => {
    var pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])');
    if (e.target.value.split(" ").length !== 1) {
      setIsPass(2)
      setDisabled(true)
    } else if (!pwdRegex.test(e.target.value)) {
      setIsPass(3)
      setDisabled(true)
    } else if (e.target.value.length < 8 || e.target.value.length > 16) {
      setIsPass(4)
      setDisabled(true)
    } else {
      setDisabled(false)
      setIsPass(0)
    }
  }
  //禁止输入中文
  const ZHReplace = (e) => {
    e.target.value = e.target.value.replace(/[\u4e00-\u9fa5]/ig, '')
  }
  const goBack = () => {
    dispatch(changeRegister(false))
    dispatch(changeshowModalActiom(true))
    setPhone(10086)
  }
  //重新发送
  const resend = () => {
    setCountDown(true)
    code(phone).then(res=>{
      console.log(res);
   })
  }
  // 倒计时
  const { Countdown } = Statistic;
  const deadline = Date.now() + 1000 * 60;
  const finish = (e) => {
    setCountDown(false)
  }
  //输入框变化时
  const inputKeyUps = (e) => {
    if(e.target.value.length>=4){
      verificationCode(phone,e.target.value).then(res=>{
        if(res.code===200){
          //验证是否已经注册
          IsRegister(phone).then(res=>{
            if(res.code===200){
              message.info('手机号已经注册已自动登录');
              dispatch(getLoginSucceedInfoAction(phone,password))
              dispatch(changeRegister(false))
            }else{
              message.info('注册新用户开发中.....')
            }
          })
        }else{
          message.error('验证码输入错误');
          e.target.value = ""
        }
      })
    }
  }
   //可移动窗体
   const onStart = (event, uiData) => {
    const { clientWidth, clientHeight } = window?.document?.documentElement;
    const targetRect = draggleRef?.current?.getBoundingClientRect();
    setBounds({
      bounds: {
        left: -targetRect?.left + uiData?.x,
        right: clientWidth - (targetRect?.right - uiData?.x),
        top: -targetRect?.top + uiData?.y,
        bottom: clientHeight - (targetRect?.bottom - uiData?.y),
      },
    });
  };
  return (
    <div>
      {/* onOk={handleOk} onCancel={handleCancel} */}
      <Modal title={
              <div
                style={{
                  width: '100%',
                  cursor: 'move',
                }}
                onFocus={() => { }}
                onBlur={() => { }}
              // end
              >
                手机号注册
            </div>
            }  onCancel={handleCancel} visible={isShowRegister} isDisabled={disabled} footer=""
            modalRender={modal => (
              <Draggable
                disabled2={disabled2}
                bounds={bounds}
                onStart={(event, uiData) => onStart(event, uiData)}
              >
                <div ref={draggleRef}>{modal}</div>
              </Draggable>
            )}
            >
        <RegisterWrapper isPass={isPass} phone={phone}>
          <Form
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            layout="vertical"
          >
            <Form.Item
              label="手机号"
              name="username"
              rules={[{ required: true, message: '手机号不能为空' }, {
                pattern: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/,
                message: '请输入正确的手机号'
              }
              ]}
            >
              <Input placeholder="请输入手机号" type="number" />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
            >
              <Input.Password placeholder="设置密码不少于8位" onKeyUp={e => ZHReplace(e)} onChange={e => inputChange(e)} />
            </Form.Item>
            <div className="rule">
              <div className="rule-item rule-item2">
                <i></i><span>密码不能包含空格</span>
              </div>
              <div className="rule-item rule-item3">
                <i></i><span>包含字母、数字、符号</span>
              </div>
              <div className="rule-item rule-item4">
                <i></i><span>密码长度为8-16位</span>
              </div>
            </div>
            <Form.Item>
              <Button type="primary" htmlType="submit" ref={nextRef} disabled={disabled} >
                下一步
             </Button>
            </Form.Item>
          </Form>
          <div className="footer" onClick={e => goBack()}>
            ＜返回登录
            </div>
        </RegisterWrapper>
        <QRCode phone={phone} isCountDown={isCountDown}>
          <div className="content">
            <p className="info">
              您的手机号:<strong>{mask(phone + "", 3, 7, "****")}</strong>
            </p>
            <p className="info hint">
              为了安全，我们会给你发送短信验证码
               </p>
          </div>
          <div className="code">
             <div className="c-word" >
             <Input type="number" onKeyUp={e => inputKeyUps(e)} />
             </div>
          </div>
          <div className="resend">
            <p onClick={resend}>重新发送</p>
            <Countdown value={deadline} format="s 秒" onFinish={finish} />
          </div>
          <Button type="primary" htmlType="submit" className="next">
            下一步
             </Button>
          <div className="footer" onClick={e => goBack()}>
            ＜返回登录
            </div>
        </QRCode>
      </Modal>
    </div>
  )
})
export default Register;